using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using UniversalAdminSystem.Application.Authentication.Interfaces;
using UniversalAdminSystem.Domian.UserManagement.ValueObj;

namespace UniversalAdminSystem.Infrastructure.Auth;

public class JwtTokenService : IJwtTokenService
{
    private readonly JwtTokenBuilder _builder;

    public JwtTokenService(JwtTokenBuilder builder)
    {
        _builder = builder;
    }

    public string GenerateToken(string userId, string roleId, UserStatus status)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, userId),
            new Claim(ClaimTypes.Role, roleId),
            new Claim(ClaimTypes.StateOrProvince, status.ToString())
        };

        return _builder.BuildToken(claims);
    }

public (string userId, string roleId, UserStatus status) ParseToken(string token)
{
    try
    {
        Console.WriteLine($"开始解析Token，长度: {token.Length}");
        
        // 检查token是否为空
        if (string.IsNullOrEmpty(token))
        {
            throw new ArgumentException("Token不能为空");
        }
        
        // 检查token格式
        var parts = token.Split('.');
        if (parts.Length != 3)
        {
            throw new ArgumentException($"Token格式错误，包含{parts.Length}个部分，应该是3个部分");
        }
        
        var handler = new JwtSecurityTokenHandler();
        
        // 检查token是否可以读取
        if (!handler.CanReadToken(token))
        {
            throw new ArgumentException("Token格式不正确，无法读取");
        }
        
        var jwt = handler.ReadJwtToken(token);
        Console.WriteLine($"JWT解析成功，Claims数量: {jwt.Claims.Count()}");
        
        var userId = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value ?? "";
        var roleId = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value ?? "";
        var status = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.StateOrProvince)?.Value ?? "";
        
        Console.WriteLine($"JWT解析 - 用户ID: {userId}, 角色ID: {roleId}, 状态: {status}");
        
        if (string.IsNullOrEmpty(status))
        {
            throw new ArgumentException("Token中缺少用户状态信息");
        }
        
        return (userId, roleId, (UserStatus)Enum.Parse(typeof(UserStatus), status));
    }
    catch (Exception ex)
    {
        Console.WriteLine($"JWT解析失败: {ex.Message}");
        Console.WriteLine($"异常类型: {ex.GetType().Name}");
        throw;
    }
}

    public string RefreshToken(string token, out string userId, out string roleId, out UserStatus status)
    {
        var (_userId, _roleId, _status) = ParseToken(token);
        userId = _userId;
        roleId = _roleId;
        status = _status;
        return GenerateToken(userId, roleId, status);
    }
}